//
//  WriteLog.m
//  Untitled
//
//  Created by  user on 11-5-7.
//  Copyright 2011 GuangZhouXuanWu. All rights reserved.
//

#import "WriteLog.h"

#import "OperationQueueShell.h"

@implementation CWriteLog
{
	NSString* _logPath;
}

static CWriteLog* s_writelog;

-(id)initWithPath:(NSString*)szPath
{
	self = [super init];
	_logPath=[szPath retain_mm];
//	m_queue=[NSOperationQueue new];
//	[m_queue setMaxConcurrentOperationCount:1];
	NSFileManager* filemanager=[NSFileManager defaultManager];
	NSArray* arFiles=[filemanager contentsOfDirectoryAtPath:szPath error:nil];
	if(arFiles.count>=14)
	{
		for(NSInteger i=arFiles.count;i>7;i--)
		{
			NSString* f=[arFiles objectAtIndex:i-1];
			[filemanager removeItemAtPath:[szPath stringByAppendingPathComponent:f] error:nil];
		}
	}
	return self;
}

-(void)dealloc
{
//	[m_queue release_mm];
	[_logPath release_mm];
	superdealloc_mm;
}

+(void)initWriteLogPath:(NSString *)szPath
{
	if(s_writelog==nil)
        s_writelog=[[CWriteLog alloc]initWithPath:szPath];
}

+(void)releaseWriteLog
{
	[s_writelog release_mm];
	s_writelog=nil;
}

+(void)writeLog:(NSString *)szLog
{
    [s_writelog writeLog:szLog];
}

-(void)writeLog:(NSString*)szLog
{
    void(^fun)()=^
    {
        @autoreleasepool
        {
            NSDate* date=[NSDate date];
            
            NSDateFormatter* formatter=[[NSDateFormatter new]autorelease];
            [formatter setDateFormat:@"yyyyMMdd"];
            NSString* szFilename=[[formatter stringFromDate:date]stringByAppendingPathExtension:@"log"];
            
            NSString* szPath=[_logPath stringByAppendingPathComponent:szFilename];
            NSFileManager* filemanager=[NSFileManager defaultManager];
            BOOL bResult=[filemanager fileExistsAtPath:szPath];
            if(YES!=bResult)
                [filemanager createFileAtPath:szPath contents:nil attributes:nil];
            NSFileHandle* handle=[NSFileHandle fileHandleForWritingAtPath:szPath];
            [handle seekToEndOfFile];
            
            [formatter setDateFormat:@"hh:mm:ss"];
            NSString* szDate=[formatter stringFromDate:date];
            NSString* szContent=[NSString stringWithFormat:@"%@ %@\r\n",szDate,szLog];
            [handle writeData:[szContent dataUsingEncoding:NSUTF8StringEncoding]];
            
            [handle closeFile];
        }
    };
    
    DispatchThread(fun);
}

@end

void RedirectNSLogInPath(NSString *logPath)
{
    freopen([logPath UTF8String],"w+",stderr);
}
